//
//  AppDelegate.m
//  DolphinMusic
//
//  Created by dllo on 15/3/21.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "AppDelegate.h"
#import "LocalMusicViewController.h"
#import "NetMusicViewController.h"
#import "FMViewController.h"
#import "SearchViewController.h"
#import "SettingViewController.h"
#import "PlayView.h"
#import "STKAudioPlayer.h"
#import "Song.h"
#import "SampleQueueId.h"
#import "MusicPlayViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "CDSideBarController.h"
#import "SDImageCache.h"
#import "DXAlertView.h"
#import "JellyAlert.h"
#import "DataBaseHandler.h"

#import <ShareSDK/ShareSDK.h>
#import "WeiboSDK.h"
#import "WeiboApi.h"
#import <TencentWeiboConnection/TencentWeiboConnection.h>


@interface AppDelegate ()<UIAlertViewDelegate>

@property (nonatomic, strong) JellyAlert *alert;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [_window release];

    

    
    
    
    
  //  UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
  //  view.backgroundColor = [UIColor yellowColor];
    /*********/
    self.alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除缓存" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"清除缓存", nil];
    
    self.alertView1 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前已是最新版本" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    
    
    
    UITabBarController *tabBarVC = [[UITabBarController alloc] init];
    self.window.rootViewController = tabBarVC;
    tabBarVC.tabBar.hidden = YES;
    [tabBarVC release];
    
    LocalMusicViewController *localMusicVC = [[LocalMusicViewController alloc] init];
    UINavigationController *localNaviVC = [[UINavigationController alloc] initWithRootViewController:localMusicVC];
    localNaviVC.navigationBar.hidden = YES;
    
    NetMusicViewController *netMusicVC = [[NetMusicViewController alloc] init];
    UINavigationController *netMusicNaviVC = [[UINavigationController alloc] initWithRootViewController:netMusicVC];
    netMusicNaviVC.navigationBar.hidden = YES;
    
    FMViewController *fmVC = [[FMViewController alloc] init];
    UINavigationController *fmNaviVC = [[UINavigationController alloc] initWithRootViewController:fmVC];
    fmNaviVC.navigationBar.hidden = YES;
    
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    UINavigationController *searchNaviVC = [[UINavigationController alloc] initWithRootViewController:searchVC];
    
    SettingViewController *settingVC = [[SettingViewController alloc] init];
    UINavigationController *settingNaviVC = [[UINavigationController alloc] initWithRootViewController:settingVC];
    
    tabBarVC.viewControllers = @[localNaviVC, netMusicNaviVC, fmNaviVC, searchNaviVC, settingNaviVC];
    [tabBarVC setSelectedIndex:1];
    
//    // 侧边栏
   
    NSArray *imageList = @[[UIImage imageNamed:@"banben1.png"], [UIImage imageNamed:@"clean3.png"], [UIImage imageNamed:@"yejian2.png"], [UIImage imageNamed:@"guanyu1.png"]];
    sideBar = [[CDSideBarController alloc] initWithImages:imageList];
    sideBar.delegate = self;
    
    [sideBar insertMenuButtonOnView:self.window atPosition:CGPointMake(self.window.frame.size.width - (self.window.frame.size.width - 210) / 2, 20)];

    sideBar.menuButton.tag = 1000;
    
    
    [localMusicVC release];
    [localNaviVC release];
    [netMusicVC release];
    [netMusicNaviVC release];
    [fmVC release];
    [fmNaviVC release];
    [searchVC release];
    [searchNaviVC release];
    [settingVC release];
    [settingNaviVC release];
    
    
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    [dbHandler openDB];
    
    [dbHandler creatTableSongCollection];
    [dbHandler creatTableFMalbumCollection];
    [dbHandler creatTableRecentPlay];
    [dbHandler creatTableFilePath];
    [dbHandler creatTableLoading];
    
    MusicPlayViewController *musicPlayVC = [MusicPlayViewController shareInstance];
    
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    
    CGFloat a = 70.0 / 667;
    PlayView *playView = [[PlayView alloc] initWithFrame:CGRectMake(0, self.window.frame.size.height * (1 - a), self.window.frame.size.width, self.window.frame.size.height * a) imageName:@"singerPlaceholder.jpg"];
    playView.tag = 10001;
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"歌曲信息" object:nil];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"更新时间" object:nil];
    [center addObserver:self selector:@selector(receiveNotification:) name:@"播放按钮" object:nil];
    
    playView.userInteractionEnabled = NO;
    playView.backgroundColor = [UIColor colorFromHexCode:@"#121a2a"];
    [self.window addSubview:playView];
    
    // 新浪微博
    // 初始化ShareSDK应用
    [ShareSDK registerApp:@"683639ff154b"];
    // 初始化社交平台
    [self initializePlat];
    
  
    return YES;
}



- (void)initializePlat
{
    /**
     连接新浪微博开放平台应用以使用相关功能，此应用需要引用SinaWeiboConnection.framework
     http://open.weibo.com上注册新浪微博开放平台应用，并将相关信息填写到以下字段
     **/
    [ShareSDK connectSinaWeiboWithAppKey:@"568898243"
                               appSecret:@"38a4f8204cc784f81f9f0daaf31e02e3"
                             redirectUri:@"http://www.sharesdk.cn"];
    
    /**
     连接腾讯微博开放平台应用以使用相关功能，此应用需要引用TencentWeiboConnection.framework
     http://dev.t.qq.com上注册腾讯微博开放平台应用，并将相关信息填写到以下字段
     
     如果需要实现SSO，需要导入libWeiboSDK.a，并引入WBApi.h，将WBApi类型传入接口
     **/
    [ShareSDK connectTencentWeiboWithAppKey:@"801307650"
                                  appSecret:@"ae36f4ee3946e1cbb98d6965b0b2ff5c"
                                redirectUri:@"http://www.sharesdk.cn"
                                   wbApiCls:[WeiboApi class]];
    
    
}
//添加两个回调方法,return的必须要ShareSDK的方法
- (BOOL)application:(UIApplication *)application
      handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url
                        wxDelegate:self];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [ShareSDK handleOpenURL:url
                 sourceApplication:sourceApplication
                        annotation:annotation
                        wxDelegate:self];
}


- (void)menuButtonClicked:(int)index
{
    // 侧边栏按钮方法
    if (index == 0) {
      
    // 弹出提示框, 当前是最新版本
        [self.alertView1 show];
        [self.window addSubview:self.alertView1];
        
    
    } else if (index == 1) {
        float size1 = [[SDImageCache sharedImageCache] checkTmpSize];
        self.alertView.message = [NSString stringWithFormat:@"目前缓存: %.2fMB", size1];
        
        [self.alertView show];
        [self.window addSubview:self.alertView];
        
    } else if (index == 2) {
        NSLog(@"222");
        // 夜间模式
        if (self.flag == NO) {
            self.window.backgroundColor = [UIColor whiteColor];
            self.window.alpha = 0.5;
            
        } else {
            self.window.backgroundColor = [UIColor whiteColor];
            self.window.alpha = 1.0;
        }
        self.flag = !self.flag;
       // NSLog(@"flag = %d", self.flag);
    } else if (index == 3) {
        NSLog(@"333");
        // 向下跳出一个页面
        self.alert = [[JellyAlert alloc]initWithFrame:self.window.frame
                                        jellyViewSize:CGSizeMake(20, 100)
                                            fillColor:[UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0]];
      
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 300)];
        label.layer.borderColor = [UIColor blackColor].CGColor;
       // label.layer.borderWidth = 2;
        label.layer.cornerRadius = 10;
        label.highlighted = YES;
        UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"label2.jpg"]];
        [label setBackgroundColor:color];
        label.textColor = [UIColor blackColor];
       // label.textColor = [UIColor colorWithRed:0.93 green:0.23 blue:0.55 alpha:1.0];
        label.text = @"      海豚音乐盒音乐是一款音频播放软件,为广大音友提供各种类别的音乐,我们以革新数字时代的时尚音乐为目标迎风远航，我们的愿景是让每个人都能体验到生活充满音乐的愉悦，让听音乐成为美好的体验。我们将使每个人都能轻松地收听喜欢的音乐，发现自己未知却已存在的新音乐，尽享完美音质带来的听觉盛宴";
        label.numberOfLines = 0;
        [label sizeToFit];
        [self.alert addSubview:label];
        [label release];
        [self.window addSubview:self.alert];
        [self.alert presentAlert];

        
    }
    
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
 
    if (buttonIndex == 0) {
        NSLog(@"buttonIndex = %ld", buttonIndex);
    } else {
        // 获得图片缓存大小
        float size1 = [[SDImageCache sharedImageCache] checkTmpSize];
            NSLog(@"size1 = %lf", size1);

        // 清除缓存
        [[SDImageCache sharedImageCache] clearDisk];
        
        
        NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSLog(@"%@", str);
        
        NSString * string;
        
        if ((NSInteger)(size1 / 4) == 0) {
            string = [NSString stringWithFormat:@"清理出%.2fMB内存", size1];
        }
        else {
         string = [NSString stringWithFormat:@"缓存清理成功, 又能多装%ld首歌了", (NSInteger)(size1 / 4)];
        }
        
        UIAlertView * alerView = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alerView show];
            
    }
}


- (void)closeAction:(UIButton *)button
{
    // 使自己消失
    NSLog(@"dismiss");
    [self.label removeFromSuperview];
}


- (void)receiveNotification:(NSNotification *)noti
{
    PlayView *playView = (PlayView *)[self.window viewWithTag:10001];
    if ([noti.name isEqualToString:@"歌曲信息"]) {
    NSArray *arr = noti.object;
    
    playView.titleLabel.text = arr[0];
    playView.authorLabel.text = arr[1];
        
        [playView.imageView setImageWithURL:[NSURL URLWithString:[arr[2] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:@"singerPlaceholder.jpg"]];
        
        
    }
    
    if ([noti.name isEqualToString:@"更新时间"])
    {
        playView.timeLabel.text = noti.object;
    }

    if ([noti.name isEqualToString:@"播放按钮"]) {
        
        playView.imageView2.image = [UIImage imageNamed:@"pause.png"];
    }
    
}


- (void)dealloc
{
    [_label release];
    [_alertView release];
    [_window release];
    [super dealloc];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
//    [application beginBackgroundTaskWithExpirationHandler:nil];
    [application beginReceivingRemoteControlEvents];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
#pragma mark - 退出的时候保存进度
    
    MusicPlayViewController *musicPlayVC = [MusicPlayViewController shareInstance];
    NSString *songid = musicPlayVC.songID;
    NSString *imageStr = musicPlayVC.imageStr;
    NSString *singerName = musicPlayVC.singerName;
    NSString *songTitle = musicPlayVC.title;
    
    NSArray *arr = @[songid, imageStr, singerName, songTitle];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    
    NSString *arrPath = [path stringByAppendingString:@"/arr.plist"];
    
    NSLog(@"Documents文件夹的路径: %@", arrPath);
    
    [arr writeToFile:arrPath atomically:YES];
    
}

@end
